package xin.marcher.module.diplomacy.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.exception.CommonErrorCodeEnum;
import xin.marcher.module.common.utils.ServletUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ⾃定义扩展sentinel的流控异常处理器
 */
@Component
public class CustomBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        JsonResult<Object> jsonResult = null;
        if (e instanceof FlowException) {
            jsonResult = JsonResult.buildError(CommonErrorCodeEnum.BLOCK_FLOW_ERROR);
        } else if (e instanceof DegradeException) {
            jsonResult = JsonResult.buildError(CommonErrorCodeEnum.BLOCK_DEGRADE_ERROR);
        } else if (e instanceof AuthorityException) {
            jsonResult = JsonResult.buildError(CommonErrorCodeEnum.BLOCK_AUTHORITY_ERROR);
        }
        httpServletResponse.setStatus(200);
        // 输出响应结果到前端
        ServletUtil.writeJsonMessage(httpServletResponse, jsonResult);
    }

}
